<template>
  <div p-5>
    <DynamicTable
      bordered
      :data-request="loadData"
      :columns="columns"
      row-key="id"
      @resize-column="handleResizeColumn"
      :scroll="{
        y: 'calc(100vh - 360px)',
      }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'status'">
          <a-switch
            v-model:checked="record.status"
            :checkedValue="1"
            :unCheckedValue="0"
            checkedChildren="启用"
            unCheckedChildren="禁用"
            width="60"
            :disabled="record.roleName === '超级管理员'"
            @click="onDisable(record)"
          />
        </template>
      </template>
      <template #toolbar>
        <a-button type="primary" @click="openUserModal({})"> 新增 </a-button>
      </template>
    </DynamicTable>
  </div>
</template>
<script setup lang="ts">
  import { Modal, message } from 'ant-design-vue';
  import { baseColumns, type TableListItem } from './columns';
  // @ts-ignore
  import { userSchemas, resetPwdSchemas } from './formSchemas';

  import {
    getTableListApi,
    updateStatusApi,
    updateUser,
    createUser,
    getDetailUser,
    getDeptList,
    getRoleList,
    deleteUserApi,
    resetPwdApi,
  } from '@/api/system/user/index';
  import {
    useTable,
    type OnChangeCallbackParams,
    type TableColumn,
  } from '@/components/core/dynamic-table';
  import { useFormModal } from '@/hooks/useModal/index';

  const [showModal] = useFormModal();

  const [DynamicTable, dynamicTableInstance] = useTable();
  const columns: TableColumn[] = [
    ...baseColumns,
    {
      title: '操作',
      align: 'left',
      width: 170,
      dataIndex: 'ACTION',
      actions: ({ record }) => [
        {
          ifShow: record.userName !== '超级管理员',
          label: '编辑',
          onClick: () => openUserModal(record),
        },
        {
          ifShow: record.userName !== '超级管理员',
          label: '删除',
          onClick: () => deleteUser(record),
        },
        {
          ifShow: record.userName !== '超级管理员',
          label: '重置密码',
          onClick: () => openResetPwdModal(record),
        },
      ],
    },
  ];

  const loadData = async (
    params,
    onChangeParams: OnChangeCallbackParams,
  ): Promise<API.TableListResult> => {
    const data = await getTableListApi(params);
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          list: data,
          ...params,
        });
      }, 500);
    });
  };

  const handleResizeColumn = (w, col) => {
    col.width = w;
  };

  // 企业状态开关变化   1.启用  2.禁用
  const onDisable = async (row: any) => {
    if (row.status == 0) {
      Modal.confirm({
        title: '确定禁用该用户？',
        centered: true,
        onOk: async () => {
          await updateStatusApi({ id: row.id, status: row.status });
          dynamicTableInstance?.reload?.();
        },
        onCancel: () => {
          row.status = 1;
        },
      });
    } else {
      updateStatusApi({ id: row.id, status: row.status })
        .then((res) => {
          if (res.code == 0) {
            dynamicTableInstance?.reload?.();
            message.success('启用成功');
          }
        })
        .catch((err) => {
          row.enableState = 0;
        });
    }
  };

  /**
   * @description 打开用户弹窗
   */
  const openUserModal = async (record: Partial<TableListItem> = {}) => {
    const [formRef] = await showModal<any>({
      modalProps: {
        title: `${record.id ? '编辑' : '新增'}用户`,
        width: 700,
        onFinish: async (values) => {
          values.id = record.id;
          await (record.id ? updateUser : createUser)(values);
          dynamicTableInstance?.reload();
        },
      },
      formProps: {
        labelWidth: 80,
        schemas: userSchemas,
        autoSubmitOnEnter: true,
      },
    });
    getDeptList().then((res) => {
      formRef?.updateSchema([
        {
          field: 'deptId',
          componentProps: {
            options: res,
          },
        },
      ]);
    });

    // 编辑隐藏初始密码字段
    if (record?.id) {
      formRef?.updateSchema([
        {
          field: 'password',
          vIf: false,
        },
        {
          field: 'userLogin',
          componentProps: {
            disabled: true,
          },
        },
      ]);
    }
    if (record?.id) {
      const data = await getDetailUser(record.id);
      formRef?.setFieldsValue(data);

      getRoleList(data.typeId).then((ret) => {
        formRef?.updateSchema([
          {
            field: 'roleId',
            componentProps: {
              options: ret,
            },
          },
        ]);
      });
    } else {
      formRef?.setFieldsValue({ password: 'fire123456' });
    }
  };

  /**
   * @description 删除用户
   */
  const deleteUser = (record: Partial<TableListItem> = {}) => {
    Modal.confirm({
      title: '确定删除该用户？',
      centered: true,
      onOk: async () => {
        await deleteUserApi(record.id);
        dynamicTableInstance?.reload?.();
      },
      onCancel: () => {},
    });
  };

  /**
   * @description 重置密码
   */
  const openResetPwdModal = async (record: Partial<TableListItem> = {}) => {
    const [formRef] = await showModal<any>({
      modalProps: {
        title: `重置密码`,
        width: 700,
        onFinish: async (values) => {
          values.id = record.id;
          let result = await resetPwdApi(values);
          if (result == 0) message.success('修改成功');
        },
      },
      formProps: {
        labelWidth: 100,
        schemas: resetPwdSchemas,
      },
    });
  };
</script>
<style scoped lang="less"></style>
